package logic

import (
	"context"
	"errors"
	"video/models/mysql"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type CollectionAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectionAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectionAddLogic {
	return &CollectionAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 收藏添加
func (l *CollectionAddLogic) CollectionAdd(in *videorpc.CollectionAddRequest) (*videorpc.CollectionAddResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.FirstUserByUserId(mysql.DB, in.UserId)
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("用户登录,不允许收藏")
	}

	var findCollection mysql.Collection
	err = findCollection.FindComment(mysql.DB, in.UserId, in.VideoId)
	if err != nil {
		return nil, err
	}
	if findCollection.ID != 0 {
		return nil, errors.New("已收藏,无需重复收藏")
	}

	collection := &mysql.Collection{
		Model:   gorm.Model{},
		VideoId: int(in.VideoId),
		UserId:  int(in.UserId),
	}
	err = collection.CommentAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("收藏失败")
	}
	return &videorpc.CollectionAddResponse{
		CollectionId: int64(collection.ID),
	}, nil
}
